<?php
/***************************************************************************
 * @Description:
 * 
 * @FileName:         Validater.php
 * @Author :          liyong5@staff.sina.com.cn
 * @CreatedTime:      2018年08月09日 星期四 18时55分11秒
 ************************************************************************/

namespace app\modules\core\models;

use Yii;
use yii\base\Model;
use yii\validators\Validator as BaseValidator;
use yii\mongodb\ActiveRecord;


class Validator extends ActiveRecord
{
    public function rules() {
        return [
            [['id', 'name', 'isBuiltIn', 'ns'], 'required'],
            ['params', 'default', 'value' => []],
            ['enable', 'string'],
            ['ns', 'validateNs'],
            ['desc', 'string'],
        ];
    }

    public function attributes() {
        return ['_id', 'id', 'name', 'desc', 'isBuiltIn', 'ns', 'params', 'enable'];
    }

    public function attributeLabels() {
        return [
            'id'        => 'ID',
            'name'      => '名称',
            'desc'      => '描述',
            'ns'        => '命名空间',
            'params'    => '验证参数',
            'enable'    => '是否启用'
        ];
    }

    public function formName() {
        return '';
    }

    public static function primaryKey() {
        return ['id'];
    }

    public function validateNs($attr, $params) {
        return class_exists($this->ns);
    }

    public static function getCoreValidators() {
        $coreValidators = BaseValidator::$builtInValidators;

        foreach ($coreValidators as $key => $validator) {
            if (is_string($validator)) {
                $coreValidators[$key] = $validator;
            }
            else if (is_array($validator) && isset($validator['class'])) {
                $coreValidators[$key] = $validator['class'];
            }
        }
        return array_flip($coreValidators);
    }
}
